package common;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author Qiqi
 * @Date 2020/11/16 17:19
 */
public class MainPage extends BasePage {

//    WebDriver webDriver;


    public MainPage() throws Exception{
        this.getLogin();
    }

    public void getCookie() throws IOException {
        webDriver = new ChromeDriver();
        webDriver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        webDriver.get("https://work.weixin.qq.com/wework_admin/frame");
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Set<Cookie> cookies = webDriver.manage().getCookies();
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        mapper.writeValue(new File("cookies.yaml"),cookies);
        System.exit(0);
    }

    public void getLogin() throws Exception {
        File file = new File("cookies.yaml");
        if (file.exists()){
            webDriver = new ChromeDriver();
            ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
            webDriver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
            webDriver.get("https://work.weixin.qq.com/wework_admin/frame");
            TypeReference<List<HashMap<String, Object>>> typeReference = new TypeReference<List<HashMap<String, Object>>>() {
            };
            List<HashMap<String, Object>> cookies = mapper.readValue(new File("cookies.yaml"), typeReference);
            cookies.forEach(cookieMap -> webDriver.manage().addCookie(new Cookie(cookieMap.get("name").toString(), cookieMap.get("value").toString())));
            webDriver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
            webDriver.navigate().refresh();
            webDriver.manage().window().maximize();

        }else {
            getCookie();
        }
    }

    public ContactPage contactDriver(){
        click(By.id("menu_contacts"));
        return new ContactPage(webDriver);
    }
}
